package com.SouthernWall_404.AgeRight.Common.Event;

import com.SouthernWall_404.AgeRight.Common.API.LockAPI.LockAPI;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.level.ChunkEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

import java.util.HashMap;
import java.util.Map;

@Mod.EventBusSubscriber
public class ChunkEvents {
    
    // 跟踪玩家最后所在的区块
    private static final Map<ServerPlayer, LevelChunk> lastPlayerChunks = new HashMap<>();
    
    @SubscribeEvent
    public static void onPlayerTick(TickEvent.PlayerTickEvent event) {
        if (event.phase == TickEvent.Phase.END && !event.player.level().isClientSide()) {
            ServerPlayer player = (ServerPlayer) event.player;
            LevelChunk currentChunk = player.level().getChunkAt(player.blockPosition());
            
            // 检查玩家是否进入了新区块
            LevelChunk lastChunk = lastPlayerChunks.get(player);
            if (lastChunk == null || !lastChunk.getPos().equals(currentChunk.getPos())) {
                // 玩家进入了新区块，发送锁数据
                LockAPI.syncLocksToPlayer(currentChunk, player);
                lastPlayerChunks.put(player, currentChunk);
            }
        }
    }
    @SubscribeEvent
    public static void onChunkLoad(ChunkEvent.Load event) {
        // 只在服务端处理区块加载事件
        if (!event.getLevel().isClientSide() && event.getChunk() instanceof LevelChunk levelChunk) {
            // 当区块加载时，同步锁数据到所有正在观看该区块的客户端
            LockAPI.syncLocksToClients(levelChunk);
        }
    }
    
    @SubscribeEvent
    public static void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event) {
        // 玩家退出时移除跟踪
        if (!event.getEntity().level().isClientSide()) {
            lastPlayerChunks.remove((ServerPlayer) event.getEntity());
        }
    }
}